#!/usr/bin/python
# -*- coding:utf-8 -*-
from mongoengine.errors import DoesNotExist
from django_mongoengine.mongo_auth.backends import MongoEngineBackend
from apps.account_manager.models import User
from apps.account_manager.account_utils import user_can_authenticate
from apps.account_manager.error_message import PasswordError, NotActiveError


class CustomBackend(MongoEngineBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = self._user_login(username, password)
        return user

    def _user_login(self, username=None, password=None):
        try:
            user = User.objects.get(username=username)
        except DoesNotExist:
            return None
        if not user.check_password(password):
            raise PasswordError("用户名或者密码错误")
        if not self.user_can_authenticate(user):
            raise NotActiveError("用户已过期或者被冻结, 请联系管理员")
        return user

    def user_can_authenticate(self, user):
        return user_can_authenticate(user)
